package com.vm.osm.business.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.vm.osm.business.common.Constants;
import com.vm.osm.business.common.ErrCode;
import com.vm.osm.business.common.exception.BusinessException;
import com.vm.osm.business.dao.*;
import com.vm.osm.business.dto.req.checkPlan.*;
import com.vm.osm.business.dto.rsp.checkPlan.*;
import com.vm.osm.business.dto.rsp.checkPlan.TaskContentType;
import com.vm.osm.business.entity.*;
import com.vm.osm.business.service.ICheckPlanService;
import com.vm.osm.business.service.IOsmIndexConfigService;
import com.vm.osm.business.util.DateFormatUtils;
import com.vm.osm.business.util.UserDataUtil;
import com.vm.osm.business.util.UuidUtil;
import com.vma.eams.spring.boot.log.LogCollector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * Created by chenzui on 2018/2/7.
 */
@Service
public class CheckPlanServiceImpl implements ICheckPlanService {
    @Autowired
    private OsmCheckPlanMapper osmCheckPlanMapper;

    @Autowired
    private OsmPlanContentMapper osmPlanContentMapper;

    @Autowired
    private OsmTaskItemMapper osmTaskItemMapper;

    @Autowired
    private OsmKpiMapper osmKpiMapper;

    @Autowired
    private OsmCheckPlanInstMapper osmCheckPlanInstMapper;

    @Autowired
    private OsmCheckItemKpiRelaMapper osmCheckItemKpiRelaMapper;

    @Autowired
    private OsmContentTypeMapper osmContentTypeMapper;

    @Autowired
    private IOsmIndexConfigService osmIndexConfigService;

    @Autowired
    private OsmOrderFlowMapper osmOrderFlowMapper;

    @Override
    public int deleteByPrimaryKey(String id) {
        return osmCheckPlanMapper.deleteByPrimaryKey(id);
    }

    @Override
    public int insert(OsmCheckPlan record) {
        return osmCheckPlanMapper.insert(record);
    }

    @Override
    public int insertSelective(OsmCheckPlan record) {
        return osmCheckPlanMapper.insertSelective(record);
    }

    @Override
    public OsmCheckPlan selectByPrimaryKey(String id) {
        return osmCheckPlanMapper.selectByPrimaryKey(id);
    }

    @Override
    public int updateByPrimaryKeySelective(OsmCheckPlan record) {
        return osmCheckPlanMapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public int updateByPrimaryKey(OsmCheckPlan record) {
        return osmCheckPlanMapper.updateByPrimaryKey(record);
    }

    @Override
    public RspCheckPlan selectCheckPlanById(String id) {
        return osmCheckPlanMapper.selectCheckPlanById(id);
    }

    @Override
    public RspCheckPlanPage findPage(String enterpriseId,Integer pageNum,Integer pageSize,String title, String planType, String status, Date startTime, Date endTime) {
        RspCheckPlanPage rspCheckPlanPage = new RspCheckPlanPage();
        Page page = PageHelper.startPage(pageNum,pageSize,true);
        List<RspCheckPlan> dataList = osmCheckPlanMapper.findPage(enterpriseId,title,planType,status,startTime,endTime);
        long current = System.currentTimeMillis();
        for(RspCheckPlan rspCheckPlan:dataList){
            if(rspCheckPlan.getStart_time().getTime() <= current && current <= rspCheckPlan.getEnd_time().getTime() && rspCheckPlan.getStatus().equals("1")){
                OsmCheckPlan plan = osmCheckPlanMapper.selectByPrimaryKey(rspCheckPlan.getId());
                plan.setStatus(new Byte("2"));//进行中
                osmCheckPlanMapper.updateByPrimaryKeySelective(plan);
                rspCheckPlan.setStatus("2");
            }
            if(rspCheckPlan.getEnd_time().getTime() <= current && rspCheckPlan.getStatus().equals("1")){
                OsmCheckPlan plan = osmCheckPlanMapper.selectByPrimaryKey(rspCheckPlan.getId());
                plan.setStatus(new Byte("3"));//已结束
                osmCheckPlanMapper.updateByPrimaryKeySelective(plan);
                rspCheckPlan.setStatus("3");
            }
        }

        rspCheckPlanPage.setData_list(dataList);
        rspCheckPlanPage.setTotal_num(page.getTotal());
        rspCheckPlanPage.setPage_num(page.getPageNum());
        rspCheckPlanPage.setPage_size(page.getPageSize());
        return rspCheckPlanPage;
    }

    @Override
    @Transactional
    public void addCheckContent(ReqAddPlanContent reqAddPlanContent,String staffId,String staffName,String enterpriseId) {
        OsmPlanContent  planContent = new OsmPlanContent();
        String contentId = UuidUtil.getRandomUuid();
        planContent.setId(contentId);
        planContent.setPlanDesc(reqAddPlanContent.getPlan_desc());
        planContent.setPlanTitle(reqAddPlanContent.getPlan_title());
        planContent.setStaffId(staffId);
        planContent.setStaffName(staffName);
        planContent.setCreateTime(new Date());
        planContent.setModifyTime(new Date());
        planContent.setLocation(reqAddPlanContent.getLocation());
        planContent.setStatus("1");
        planContent.setLocationX(reqAddPlanContent.getLocation_x());
        planContent.setLocationY(reqAddPlanContent.getLocation_y());
        planContent.setEnterpriseId(enterpriseId);
        osmPlanContentMapper.insert(planContent);

        List<TaskContentType> types  = reqAddPlanContent.getTypes();
        for (TaskContentType type:types) {
            OsmContentType osmContentType = new OsmContentType();
            osmContentType.setCreateTime(new Date());
            osmContentType.setUpdateTime(new Date());
            osmContentType.setId(UuidUtil.getRandomUuid());
            osmContentType.setContentId(planContent.getId());
            osmContentType.setStatus("1");
            osmContentType.setTypeName(type.getType_name());
            osmContentTypeMapper.insert(osmContentType);
            List<TaskItem> items = type.getTask_items();
            for(TaskItem item:items){
                OsmTaskItem record = new OsmTaskItem();
                String taskId = UuidUtil.getRandomUuid();
                record.setId(taskId);
                record.setCreateTime(new Date());
                record.setUpdateTime(new Date());
                record.setPlanTypeId(osmContentType.getId());
                record.setItemName(item.getItem_name());
                record.setItemLocation(item.getItem_location());
                osmTaskItemMapper.insert(record);
                List<KpiItem> taskKpis =  item.getKpis();
                for (KpiItem kpi:taskKpis) {
                    OsmCheckItemKpiRela rela = new OsmCheckItemKpiRela();
                    rela.setStatus(new Byte("1"));
                    rela.setItemId(taskId);
                    rela.setKpiId(kpi.getKpi_id());
                    rela.setId(UuidUtil.getRandomUuid());
                    rela.setCreateTime(new Date());
                    rela.setUpdateTime(new Date());

                    OsmKpi osmKpi = osmKpiMapper.selectByPrimaryKey(kpi.getKpi_id());

                    rela.setKpiVersion(osmKpi.getVersion());

                    osmCheckItemKpiRelaMapper.insert(rela);
                }

            }


        }
        LogCollector.INSTANCE.put("巡检内容",planContent.getPlanTitle());

    }

    @Override
    @Transactional
    public void updateCheckContent(ReqUpdatePlanContent reqUpdatePlanContent, String staffId, String staffName,String enterpriseId) {
        OsmPlanContent content = osmPlanContentMapper.selectByPrimaryKey(reqUpdatePlanContent.getId());
        content.setStatus("0");
        osmPlanContentMapper.updateByPrimaryKeySelective(content);

        OsmPlanContent  planContent = new OsmPlanContent();
        String contentId = UuidUtil.getRandomUuid();
        planContent.setId(contentId);
        planContent.setPlanDesc(reqUpdatePlanContent.getPlan_desc());
        planContent.setPlanTitle(reqUpdatePlanContent.getPlan_title());
        planContent.setStaffId(staffId);
        planContent.setStaffName(staffName);
        planContent.setCreateTime(new Date());
        planContent.setModifyTime(new Date());
        planContent.setStatus("1");
        planContent.setEnterpriseId(enterpriseId);
        planContent.setLocation(reqUpdatePlanContent.getLocation());
        planContent.setLocationX(reqUpdatePlanContent.getLocation_x());
        planContent.setLocationY(reqUpdatePlanContent.getLocation_y());
        osmPlanContentMapper.insert(planContent);

        List<TaskContentType> types  = reqUpdatePlanContent.getTypes();
        for (TaskContentType type:types) {
            OsmContentType osmContentType = new OsmContentType();
            osmContentType.setCreateTime(new Date());
            osmContentType.setUpdateTime(new Date());
            osmContentType.setId(UuidUtil.getRandomUuid());
            osmContentType.setContentId(planContent.getId());
            osmContentType.setStatus("1");
            osmContentTypeMapper.insertSelective(osmContentType);
            List<TaskItem> items = type.getTask_items();
            for(TaskItem item:items){
                OsmTaskItem record = new OsmTaskItem();
                String taskId = UuidUtil.getRandomUuid();
                record.setId(taskId);
                record.setCreateTime(new Date());
                record.setUpdateTime(new Date());
                record.setPlanTypeId(osmContentType.getId());
                record.setItemName(item.getItem_name());
                record.setItemLocation(item.getItem_location());
                osmTaskItemMapper.insert(record);
                List<KpiItem> taskKpis =  item.getKpis();
                for (KpiItem kpi:taskKpis) {
                    OsmCheckItemKpiRela rela = new OsmCheckItemKpiRela();
                    rela.setStatus(new Byte("1"));
                    rela.setItemId(taskId);
                    rela.setKpiId(kpi.getKpi_id());
                    rela.setId(UuidUtil.getRandomUuid());
                    rela.setCreateTime(new Date());
                    rela.setUpdateTime(new Date());
                    OsmKpi osmKpi = osmKpiMapper.selectByPrimaryKey(kpi.getKpi_id());
                    rela.setKpiVersion(osmKpi.getVersion());
                    osmCheckItemKpiRelaMapper.insert(rela);
                }

            }


        }

        LogCollector.INSTANCE.put("巡检内容",planContent.getPlanTitle());

    }


    @Override
    public RspPlanContentPage findContentByPage(Integer pageNum, Integer pageSize, String planTitle,String enterpriseId) {
        RspPlanContentPage planContentPage = new RspPlanContentPage();
        Page page = PageHelper.startPage(pageNum,pageSize,true);
        List<PlanContent> dataList = osmPlanContentMapper.queryPlanContentByTitle(planTitle,enterpriseId);
        planContentPage.setData_list(dataList);
        planContentPage.setTotal_num(page.getTotal());
        planContentPage.setPage_num(page.getPageNum());
        planContentPage.setPage_size(page.getPageSize());
        return planContentPage;
    }

    @Override
    public void deleteContentByIds(String ids) {
        String[] idArr = ids.split(",");

        for(int i=0;i<idArr.length;i++){
            OsmPlanContent content = osmPlanContentMapper.selectByPrimaryKey(idArr[i]);
            content.setStatus("0");
            osmPlanContentMapper.updateByPrimaryKeySelective(content);
            // TODO: 2018/3/12 删除巡检内容相关的数据
            LogCollector.INSTANCE.put("巡检内容",content.getPlanTitle());

        }

    }

    @Override
    public RspContentDetail getContentById(String id) {
        RspContentDetail detail = new RspContentDetail();
        OsmPlanContent content = osmPlanContentMapper.selectByPrimaryKey(id);
        detail.setPlan_desc(content.getPlanDesc());
        detail.setPlan_title(content.getPlanTitle());
        detail.setPlan_type("...");
        detail.setLocation(content.getLocation());
        detail.setLocation_x(content.getLocationX());
        detail.setLocation_y(content.getLocationY());
        List<TaskContentType> types = osmContentTypeMapper.queryTypesByContentId(content.getId());

        for(TaskContentType type:types){
            List<TaskItem> taskItemList = osmTaskItemMapper.queryTaskByTypeId(type.getId());

            for(TaskItem item : taskItemList){
                List<KpiItem> kpis = osmCheckItemKpiRelaMapper.queryKpisByTaskId(item.getId());
                for(KpiItem kpi:kpis){
                    List<String> valueList = osmKpiMapper.getKpiValuesById(kpi.getKpi_id(),kpi.getKpi_version());
                    kpi.setItems(valueList);
                }
                item.setKpis(kpis);
            }
            type.setTask_items(taskItemList);
        }



//        detail.setTaskItemList(taskItemList);
        detail.setTypes(types);
        return detail;
    }

    @Override
    public void handCheckPlanAction(String type, String id) {
        OsmCheckPlan checkPlan = osmCheckPlanMapper.selectByPrimaryKey(id);
        if("1".equals(type)){
            //暂停
            checkPlan.setStatus(new Byte("4"));
            osmCheckPlanMapper.updateByPrimaryKeySelective(checkPlan);
            LogCollector.INSTANCE.put("操作","暂停");
        }else if("2".equals(type)){
            //删除
            checkPlan.setStatus(new Byte("-1"));
            osmCheckPlanMapper.updateByPrimaryKeySelective(checkPlan);
            LogCollector.INSTANCE.put("操作","删除");
        }else if("3".equals(type)){
            //发布
            if(Constants.PLAN_TYPE_BY_ONE.equals(checkPlan.getPlanType().toString())){
                OsmCheckPlanInst inst = new OsmCheckPlanInst();
                inst.setCreateTime(new Date());
                inst.setCheckPlanId(checkPlan.getId());
                inst.setIsComplete("0");
                inst.setUpdateTime(new Date());
                inst.setId(UuidUtil.getRandomUuid());
                osmCheckPlanInstMapper.insertSelective(inst);
                LogCollector.INSTANCE.put("操作","发布");
            }
        }
        LogCollector.INSTANCE.put("计划名称",checkPlan.getPlanTitle());

    }

    @Override
    public void createCheckPlan(ReqAddCheckPlan reqAddCheckPlan) {
        // TODO: 2018/4/1 巡检单 
        OsmCheckPlan checkPlan = new OsmCheckPlan();
        checkPlan.setCreateTime(new Date());
        checkPlan.setPlanTitle(reqAddCheckPlan.getTitle());
        checkPlan.setModifyTime(new Date());
        checkPlan.setEndTime(DateFormatUtils.parse(reqAddCheckPlan.getEnd_time()));
        checkPlan.setExcuteEndTime((reqAddCheckPlan.getExcute_end_time()==null||reqAddCheckPlan.getExcute_end_time() == "")?reqAddCheckPlan.getEnd_time():reqAddCheckPlan.getExcute_end_time());
        checkPlan.setExcuteStartTime((reqAddCheckPlan.getExcute_start_time()==null||reqAddCheckPlan.getExcute_start_time() == "")?reqAddCheckPlan.getStart_time():reqAddCheckPlan.getExcute_start_time());
        checkPlan.setStartTime(DateFormatUtils.parse(reqAddCheckPlan.getStart_time()));
        checkPlan.setId(UuidUtil.getRandomUuid());
        checkPlan.setIntervalTime(reqAddCheckPlan.getInterval_time());
        checkPlan.setPlanContent(reqAddCheckPlan.getContent_id());
        checkPlan.setPlanType(Integer.valueOf(reqAddCheckPlan.getPlan_type()));
        checkPlan.setExcuteManName(reqAddCheckPlan.getExcute_man_name());

        checkPlan.setExcuteManType(new Byte(reqAddCheckPlan.getExcute_man_type()));
        checkPlan.setStatus(new Byte(reqAddCheckPlan.getStatus()));
        checkPlan.setSubmitStaffName(reqAddCheckPlan.getStaff_name());
        checkPlan.setSubmitStaffId(reqAddCheckPlan.getStaff_id());
        checkPlan.setExcuteStaffId(reqAddCheckPlan.getExcute_man_id());
        checkPlan.setLinkPhone(reqAddCheckPlan.getPhone());
        checkPlan.setLinkMan(reqAddCheckPlan.getStaff_name());
        checkPlan.setEnterpriseId(reqAddCheckPlan.getEnterprise_id());
        checkPlan.setExcuteTmeInfo(reqAddCheckPlan.getExcute_time_info());
        int res = osmCheckPlanMapper.insert(checkPlan);
        if (res == 0){
            throw new BusinessException(ErrCode.ADD_DATA_FAIL.toString());
        }

        if("1".equals(reqAddCheckPlan.getStatus())){
            OsmCheckPlanInst inst = new OsmCheckPlanInst();
            inst.setUpdateTime(new Date());
            inst.setIsComplete("0");
            inst.setCreateTime(new Date());
            inst.setCheckPlanId(checkPlan.getId());
            inst.setCheckTitle(checkPlan.getPlanTitle());
            inst.setPlanExcuteTime(reqAddCheckPlan.getExcute_start_time());
            inst.setId(UuidUtil.getRandomUuid());

            String orderNbr = osmIndexConfigService.getIndex(reqAddCheckPlan.getEnterprise_id(),"XJ"+DateFormatUtils.formate(new Date(),DateFormatUtils.SPLIT_PATTERN_MONTH));

            inst.setOrderNbr(orderNbr);
            inst.setPlanExcuteTime(checkPlan.getExcuteStartTime());

            if(reqAddCheckPlan.getExcute_man_type().equals("2")){
                //派给外部服务商
                inst.setEnterpriseId(checkPlan.getExcuteStaffId());
                inst.setStatus("12");//待受理
                inst.setDispatchTime(new Date());
                inst.setAcceptStaffId("");
                inst.setAcceptStaffName("");
                inst.setSourceEnterpriseId(reqAddCheckPlan.getEnterprise_id());
            }else {
                inst.setEnterpriseId(checkPlan.getEnterpriseId());
                inst.setStatus("5");//待接单
                inst.setDispatchTime(new Date());
                inst.setAcceptStaffId(checkPlan.getExcuteStaffId());
                inst.setAcceptStaffName(checkPlan.getExcuteManName());
            }
            res = osmCheckPlanInstMapper.insertSelective(inst);
            if (res == 0){
                throw new BusinessException(ErrCode.ADD_DATA_FAIL.toString());
            }

            OsmOrderFlow flow = new OsmOrderFlow();
            flow.setCreateTime(Integer.valueOf(String.valueOf(new Date().getTime()/1000)));
            flow.setOperateUserId(reqAddCheckPlan.getStaff_id());
            flow.setUpdateTime(Integer.valueOf(String.valueOf(new Date().getTime()/1000)));
            flow.setId(UuidUtil.getRandomUuid());
            flow.setOrderId(inst.getId());
            flow.setStatus(new Byte("1"));
            flow.setOperateUserName(reqAddCheckPlan.getStaff_name());
            flow.setSimpleDesc("提交了工单");
            osmOrderFlowMapper.insertSelective(flow);
            LogCollector.INSTANCE.put("计划名称",checkPlan.getPlanTitle());
        }
    }

    @Override
    public List<EquTypeKpis> queryKpiByEquType(String enterpriseId,List<EquTypeKpis> types) {
        for(EquTypeKpis type:types){
            List<KpiItem> kpiItems = osmKpiMapper.getKpiByCond(type.getEqu_type_id(),enterpriseId,null );
            for (KpiItem ki:kpiItems) {
                List<String> values = osmKpiMapper.getKpiValuesById(ki.getKpi_id(),ki.getKpi_version());
                ki.setItems(values);
            }
            type.setKpiItems(kpiItems);
        }
        return types;
    }

    @Override
    public List<OsmCheckPlan> findAll() {
        return osmCheckPlanMapper.findAll();
    }

    @Override
    public OsmCheckPlanInst selectFirst(String checkPlanId) {
        return osmCheckPlanInstMapper.selectFirst(checkPlanId);
    }

    @Override
    public void updateCheckPlan(ReqUpdateCheckPlan reqUpdateCheckPlan, HttpServletRequest request) {
        OsmCheckPlan checkPlan = osmCheckPlanMapper.selectByPrimaryKey(reqUpdateCheckPlan.getId());
        if (checkPlan == null){
            throw new BusinessException(ErrCode.DATA_NOT_FOUND.toString());
        }
        checkPlan.setPlanTitle(reqUpdateCheckPlan.getTitle());
        checkPlan.setModifyTime(new Date());
        checkPlan.setEndTime(DateFormatUtils.parse(reqUpdateCheckPlan.getEnd_time()));
        checkPlan.setExcuteEndTime(reqUpdateCheckPlan.getExcute_end_time());
        checkPlan.setExcuteStartTime(reqUpdateCheckPlan.getExcute_start_time());
        checkPlan.setStartTime(DateFormatUtils.parse(reqUpdateCheckPlan.getStart_time()));
        checkPlan.setIntervalTime(reqUpdateCheckPlan.getInterval_time());
        checkPlan.setPlanContent(reqUpdateCheckPlan.getContent_id());
        checkPlan.setStatus(new Byte(reqUpdateCheckPlan.getStatus()));

        checkPlan.setPlanType(Integer.valueOf(reqUpdateCheckPlan.getPlan_type()));
        checkPlan.setExcuteManName(reqUpdateCheckPlan.getExcute_man_name());
        checkPlan.setExcuteManType(new Byte(reqUpdateCheckPlan.getExcute_man_type()));
        checkPlan.setExcuteTmeInfo(reqUpdateCheckPlan.getExcute_time_info());
        int res = osmCheckPlanMapper.updateByPrimaryKeySelective(checkPlan);
        if (res == 0){
            throw new BusinessException(ErrCode.UPDATE_DATA_FAIL.toString());
        }
        if("1".equals(reqUpdateCheckPlan.getStatus())){


            OsmCheckPlanInst inst = new OsmCheckPlanInst();
            inst.setUpdateTime(new Date());
            inst.setIsComplete("0");
            inst.setCreateTime(new Date());
            inst.setCheckPlanId(checkPlan.getId());
            inst.setCheckTitle(checkPlan.getPlanTitle());
            inst.setPlanExcuteTime(reqUpdateCheckPlan.getExcute_start_time());
            inst.setId(UuidUtil.getRandomUuid());

            String orderNbr = osmIndexConfigService.getIndex(UserDataUtil.getUserSelectedEnterpriseId(request),"XJ"+DateFormatUtils.formate(new Date(),DateFormatUtils.SPLIT_PATTERN_MONTH));

            inst.setOrderNbr(orderNbr);
            inst.setPlanExcuteTime(checkPlan.getExcuteStartTime());

            if(reqUpdateCheckPlan.getExcute_man_type().equals("2")){
                //派给外部服务商
                inst.setEnterpriseId(checkPlan.getExcuteStaffId());
                inst.setStatus("12");//待受理
                inst.setDispatchTime(new Date());
                inst.setAcceptStaffId("");
                inst.setAcceptStaffName("");
            }else {
                inst.setEnterpriseId(checkPlan.getEnterpriseId());
                inst.setStatus("5");//待接单
                inst.setDispatchTime(new Date());
                inst.setAcceptStaffId(checkPlan.getExcuteStaffId());
                inst.setAcceptStaffName(checkPlan.getExcuteManName());
            }
            res = osmCheckPlanInstMapper.insertSelective(inst);
            if (res == 0){
                throw new BusinessException(ErrCode.ADD_DATA_FAIL.toString());
            }

            OsmOrderFlow flow = new OsmOrderFlow();
            flow.setCreateTime(Integer.valueOf(String.valueOf(new Date().getTime()/1000)));
            flow.setOperateUserId(UserDataUtil.getStaffId(request));
            flow.setUpdateTime(Integer.valueOf(String.valueOf(new Date().getTime()/1000)));
            flow.setId(UuidUtil.getRandomUuid());
            flow.setOrderId(inst.getId());
            flow.setStatus(new Byte("1"));
            flow.setOperateUserName(UserDataUtil.getStaffName(request));
            flow.setSimpleDesc("提交了工单");
            osmOrderFlowMapper.insertSelective(flow);
            LogCollector.INSTANCE.put("计划名称",checkPlan.getPlanTitle());
        }
    }


}
